package com.dyy.AI_System.controller;


import com.dyy.AI_System.domain.po.Departments;
import com.dyy.AI_System.domain.vo.ApiResponse;
import com.dyy.AI_System.service.IDepartmentsService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-10-13
 */
@Tag(name = "部门管理", description = "部门相关的CRUD操作API")
@RestController
@RequestMapping("/departments")
public class DepartmentsController {

    @Autowired
    private IDepartmentsService departmentsService;

    /**
     * 获取所有部门
     */
    @Operation(summary = "获取所有部门", description = "查询系统中所有的部门信息")
    @GetMapping
    public ResponseEntity<ApiResponse<List<Departments>>> getAllDepartments() {
        List<Departments> departments = departmentsService.list();
        return ResponseEntity.ok(ApiResponse.success(departments));
    }

    /**
     * 根据ID获取部门
     */
    @Operation(summary = "根据ID获取部门", description = "根据部门ID查询特定部门的详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Departments>> getDepartmentById(@PathVariable("id") Long id) {
        Departments department = departmentsService.getById(id);
        if (department == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的部门"));
        }
        return ResponseEntity.ok(ApiResponse.success(department));
    }

    /**
     * 分页查询部门
     */
    @Operation(summary = "分页查询部门", description = "分页查询部门列表，支持关键词搜索")
    @GetMapping("/page")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDepartmentsByPage(
            @RequestParam(defaultValue = "1", name = "page") Integer pageNum,
            @RequestParam(defaultValue = "10", name = "size") Integer pageSize,
            @RequestParam(required = false, name = "keyword") String keyword) {

        IPage<Departments> page = departmentsService.pageQuery(pageNum, pageSize, keyword);

        // 构建返回结果对象
        Map<String, Object> result = new HashMap<>();
        result.put("list", page.getRecords());
        result.put("total", page.getTotal());
        result.put("page", pageNum);
        result.put("size", pageSize);

        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 获取部门树结构
     */
    @Operation(summary = "获取部门树结构", description = "获取部门的树形结构数据")
    @GetMapping("/tree")
    public ResponseEntity<ApiResponse<List<Departments>>> getDepartmentTree() {
        List<Departments> departmentTree = departmentsService.getDepartmentTree();
        return ResponseEntity.ok(ApiResponse.success(departmentTree));
    }

    /**
     * 创建新部门
     */
    @Operation(summary = "创建新部门", description = "添加一个新的部门到系统中")
    @PostMapping
    public ResponseEntity<ApiResponse<Departments>> createDepartment(@RequestBody Departments department) {
        // 验证必要字段
        if (department.getName() == null || department.getName().trim().isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.fail(400, "部门名称不能为空"));
        }

        // 默认设置
        if (department.getParentId() == null) {
            department.setParentId(0L); // 默认为根部门
        }
        if (department.getIsActive() == null) {
            department.setIsActive(true); // 默认激活
        }
        if (department.getSortOrder() == null) {
            department.setSortOrder(0); // 默认排序
        }
        department.setCreatedAt(LocalDateTime.now());
        department.setUpdatedAt(LocalDateTime.now());

        boolean saved = departmentsService.save(department);
        if (saved) {
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ApiResponse.success("创建成功", department));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "创建失败"));
        }
    }

    /**
     * 更新部门信息
     */
    @Operation(summary = "更新部门信息", description = "更新指定ID部门的详细信息")
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> updateDepartment(
            @PathVariable("id") Long id,
            @RequestBody Departments department) {
        // 检查部门是否存在
        Departments existingDepartment = departmentsService.getById(id);
        if (existingDepartment == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的部门"));
        }

        // 设置ID以确保更新正确的部门
        department.setId(id);
        department.setUpdatedAt(LocalDateTime.now());

        boolean updated = departmentsService.updateById(department);
        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "更新失败"));
        }
    }

    /**
     * 更新部门状态
     */
    @Operation(summary = "更新部门状态", description = "激活或禁用指定ID的部门")
    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Object>> updateDepartmentStatus(
            @PathVariable("id") Long id,
            @RequestParam("isActive") Boolean isActive) {
        boolean updated = departmentsService.updateStatus(id, isActive);

        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("状态更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "状态更新失败"));
        }
    }

    /**
     * 删除部门
     */
    @Operation(summary = "删除部门", description = "从系统中删除指定ID的部门")
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> deleteDepartment(@PathVariable("id") Long id) {
        boolean deleted = departmentsService.removeById(id);
        if (deleted) {
            return ResponseEntity.ok(ApiResponse.success("删除成功", null));
        } else {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的部门，删除失败"));
        }
    }

    /**
     * 批量删除部门
     */
    @Operation(summary = "批量删除部门", description = "从系统中批量删除多个部门")
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Object>> batchDeleteDepartments(@RequestBody List<Long> ids) {
        boolean deleted = departmentsService.batchDelete(ids);

        if (deleted) {
            return ResponseEntity.ok(ApiResponse.success("批量删除成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "批量删除失败"));
        }
    }
}
